package 临时工具.粮仓.粉尘检测;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ServerReceiver {
    private static Map<Byte, String> NAME_MAP=new HashMap<Byte, String>(){{
        put((byte)0x01,"二氧化碳浓度");
        put((byte)0x02,"PM2.5");
        put((byte)0x03,"大气温度");
        put((byte)0x04,"大气相对湿度");
        put((byte)0x05,"TVOC");
        put((byte)0x06,"甲醛浓度");
        put((byte)0x07,"噪音");
        put((byte)0x08,"大气压");
        put((byte)0x09,"CO");
        put((byte)0x0A,"PM10");
        put((byte)0x0B,"Smoke");
        put((byte)0x0C,"CH4");
        put((byte)0x0D,"SO2");
        put((byte)0x0E,"NO2");
        put((byte)0x0F,"O3");
        put((byte)0x10,"油烟浓度");
        put((byte)0x11,"颗粒物浓度");
        put((byte)0x12,"风速");
        put((byte)0x13,"风向");
        put((byte)0x14,"氨气");
        put((byte)0x15,"硫化氢");
        put((byte)0x16,"氧气");
        put((byte)0x17,"负氧离子");
        put((byte)0x18,"TSP（粉尘）");
        put((byte)0x19,"光照度");
        put((byte)0x1A,"太阳辐射量");
        put((byte)0x1B,"起始X");
        put((byte)0x20,"现在Z");
        put((byte)0x21,"PID");}
    };
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(8888);
        System.out.println("服务器启动，等待连接...");

        Socket socket = server.accept();
        InputStream in = socket.getInputStream();

        byte[] buffer = new byte[1024];
        int len = in.read(buffer);

        if (buffer[0] != 0x55 || buffer[1] != (byte) 0xAA) {
            System.out.println("帧头错误");
            return;
        }

        int length = buffer[2] & 0xFF;
        byte[] dataToCheck = Arrays.copyOfRange(buffer, 2, 2 + length);
        int crcCheck = CRC16Util.calculateCRC16(dataToCheck, dataToCheck.length);
        int crcReceived = ((buffer[2 + length + 1] & 0xFF) << 8) | (buffer[2 + length] & 0xFF);

        if (crcCheck != crcReceived) {
            System.out.println("CRC 校验失败");
            return;
        }

        // 解析设备ID
        byte[] devIdBytes = Arrays.copyOfRange(buffer, 3, 11);
        String devId = new String(devIdBytes);
        System.out.println("设备ID: " + devId);

        int sensorCount = buffer[11] & 0xFF;
        int pos = 12;

        for (int i = 0; i < sensorCount; i++) {
            int type = buffer[pos++] & 0xFF;
            byte[] floatBytes = Arrays.copyOfRange(buffer, pos, pos + 4);
            float value = FloatUtil.bytesToFloat(floatBytes);
            pos += 4;
            System.out.printf("传感器类型: 0x%02X("+NAME_MAP.get((byte)type)+"), 数据: %.2f%n", type, value);
        }

        socket.close();
        server.close();
    }
}
